//会员卡中心
const app = getApp()
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx.js');
Page({
  data: {
    scene: "",
    showPhonePop: false,
    showLoginPop: false,
    isShowHome: false,
    tel: "",
    scoreNum: '',
    avatar: "",
    userInfo: {},
    isGetCard: false,
    city: "",
    openid: "",
    sdkversion: "",
    isFirPage: false,
    isLogin: true,
    isDisableLog: false,
    isDisableReg: false,
    showMemberCardPop:false
  },
  onLoad: function(options = {}) {
    this.setData({
      scene: options.scene == undefined ? '' : options.scene,
      sdkversion: app.globalData.sdkversion,
      qrcodePath: common.basePath + 'membercard/barcode/mobile/',
    })
    this.setData({
      isFirPage: getCurrentPages().length > 1 && app.globalData.wxversion > 700 ? false : true
    })

  },
  onShow: function() {
    this.locateCur();
  },
  backToHome() {
    app.globalData.skipType = 0;
    wx.switchTab({
      url: '../index/index',
    })
  },
  goToTickets() {
    wx.navigateTo({
      url: '../user_center/userVouchers',
    })
  },
  showCheckTel() {
    wx.navigateTo({
      url: '../common/register',
    })
    this.setData({
      showPhonePop: false
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  getPhoneNumber: function(e) {
    this.setData({
      isDisableReg: true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              that.setData({
                tel: res.data.data.member.cellphone,
                avatar: res.data.data.avatar,
                userInfo: res.data.data,
                isLogin: true,
                isDisableReg: false
              })
              if (that.data.scene == 'xmmember' && app.globalData.sceneId == 1047) {
                that.selectComponent("#redPacketsPool").showRedPackets();
              } else if (that.data.scene == 'member') {
                that.selectComponent("#redPacketsPool").showRedPackets();
              }
              this.getScoreCardNum(res.data.data.member.cellphone);
              this.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail: res => {
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true 
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.checkRegister();
      this.setData({
        showLoginPop: false,
        isDisableLog: false
      })
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        this.setData({
          showLoginPop: false
        })
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          this.setData({
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            tel: res.data.member.cellphone,
            avatar: res.data.avatar,
            userInfo: res.data,
            showPhonePop: false,
            isLogin: true
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              if (this.data.scene == 'xmmember' && app.globalData.sceneId == 1047) {
                this.selectComponent("#redPacketsPool").showRedPackets();
              } else if (this.data.scene == 'member') {
                this.selectComponent("#redPacketsPool").showRedPackets();

              }
            }
          })
          this.getScoreCardNum(res.data.member.cellphone);
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  locateCur() {
    var that = this;
    // wx.getLocation({
    //   type: 'gcj02',
    //   success: function(res) {
    var gdMap = new amapFile.AMapWX({
      key: common.gdKey
    });
    gdMap.getRegeo({
      success: resp => {
        that.data.city = resp[0].regeocodeData.addressComponent.city;
        // app.globalData.city = resp[0].regeocodeData.addressComponent.city;
        app.globalData.locateLongitude = resp[0].longitude;
        app.globalData.locateLatitude = resp[0].latitude;
        app.globalData.locateCity = resp[0].regeocodeData.addressComponent.city;
        app.globalData.locateProvince = resp[0].regeocodeData.addressComponent.province;
        if (that.data.scene != undefined) {
          that.checkRegister();
        } else {
          wx.getStorage({
            key: 'userInfo',
            success: res => {
              that.setData({
                tel: res.data.member.cellphone,
                avatar: res.data.avatar,
                userInfo: res.data
              })
              that.getScoreCardNum(res.data.member.cellphone)
            },
            fail: res => {
              that.checkRegister();
            }
          })
        }
      },
      fail: info => {
        that.setData({
          isLocate: false,
          showLoginPop: false
        })
        app.globalData.isLocate = false
      }
    })
  },
  getScoreCardNum(tel) {
    server.postJSON(common.basePath + 'membercard/getscorecard', {
      "mobile": tel,
      "city": this.data.city
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          scoreNum: res.data.data.score,
          showMemberCardPop: res.data.data.wx_card_id==''?true:false
        })
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  goToWechat() {
    server.postJSON(common.storePath + 'order/offlinepay', {}, res => {
      var postParam = res.data.data;
      wx.openOfflinePayView({
        'appId': postParam.appId,
        'timeStamp': postParam.timeStamp,
        'nonceStr': postParam.nonceStr,
        'package': postParam.package,
        'signType': postParam.signType,
        'paySign': postParam.paySign,
        'success': function(res) {},
        'fail': function(res) {

        },
        'complete': function(res) {
        }
      })
    })
  },
  getMemberCard() {
    this.setData({
      isGetCard: true
    })
    server.postJSON(common.basePath + 'membercard/addwxcard/', {
      "mobile": this.data.tel,
      "city": this.data.city
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          isGetCard: false
        })
        var data = res.data.data;
        wx.addCard({
          cardList: [{
            cardId: data.cardId,
            cardExt: JSON.stringify({
              code: data.code,
              timestamp: data.timestamp,
              nonce_str: data.nonce_str,
              signature: data.signature
            })
          }], // 需要添加的卡券列表
          success: res => {
            this.recordGetCard(this.data.tel, data.cardId, data.code);
            this.getScoreCardNum(this.data.tel)
          },
          fail: function(res) {
            console.log(res)
          },
          complete: function(res) {

          }
        });
      } else {
        this.setData({
          isGetCard: false
        })
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  recordGetCard(tel, cardid, code) {
    server.postJSON(common.basePath + 'membercard/wxcardsucc/', {
      "mobile": tel,
      "wx_card_id": cardid,
      "openid": app.globalData.openid,
      "code": code
    }, res => {
      if (res.data.errno == '0') {
        wx.openCard({
          cardList: [{
            cardId: cardid,
            code: code
          }]
        });
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  backPrev() {
    wx.navigateBack()
  },
  goUserInfoDetail() {
    wx.navigateTo({
      url: '../../user_center/pages/userinfoDetail',
    })
  },
  showLoginPop() {
    this.checkRegister();
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isLogin: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  },
  hideMemberCardPop(){
    this.setData({
      showMemberCardPop:false
    })
  },
  goToIndex(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  }

})